#!/bin/sh
# 编译安装Msmtp
App=msmtp
AppName=Msmtp
AppBase=/App
AppDir=$AppBase/$App
AppProg=$AppDir/bin/msmtp
AppSrcBase=/App/src
AppSrcFile=$App-*.tar.*
AppSrcDir=$(find $AppSrcBase -maxdepth 1 -name "$AppSrcFile" -type f 2> /dev/null | sed -e 's/.tar.*$//' -e 's/^.\///')

RemoveFlag=0
InstallFlag=0

# 查询状态
fstatus()
{
    test -d "$AppDir" && echo "$AppName 已安装" || echo "$AppName 未安装"
}

# 删除
fremove()
{
    RemoveFlag=1

    test -d "$AppDir" && rm -rf $AppDir
    [ $? -eq 0 ] && echo "删除 $AppName" || echo "$AppName 未安装"
    
    test -f $HOME/.msmtprc && rm -rf $HOME/.msmtprc
    [ $? -eq 0 ] && echo "删除 $AppName 配置" || echo "$AppName 配置不存在"

    test -f $HOME/.muttrc && rm -rf $HOME/.muttrc
    [ $? -eq 0 ] && echo "删除 Mutt 配置" || echo "Mutt 配置不存在"
}

# 备份
fbackup()
{
    Day=$(date +%Y-%m-%d)
    BackupFile=$App-$Day.tgz

    if [ -f "$AppProg" ]; then
        cd $AppBase
        tar zcvf $BackupFile --exclude=*.log $App --backup=numbered
        [ $? -eq 0 ] && echo "$AppName 备份成功" || echo "$AppName 备份失败"
    else
        echo "$AppName 未安装"
    fi
}

# 安装
finstall()
{
    InstallFlag=1

    test -d "$AppDir" && echo "$AppName 已安装"
    [ $? -ne 0 ] && fupdate && fcpconf
}

# 拷贝配置
fcpconf()
{
    cp -vf --backup=numbered $ScriptDir/msmtprc $HOME/.msmtprc
    cp -vf --backup=numbered $ScriptDir/muttrc $HOME/.muttrc
    sed -i "s#set sendmail=\"/App/msmtp/bin/msmtp\"#set sendmail=\"$AppProg\"#" $HOME/.muttrc
    chmod 600 $HOME/.msmtprc $HOME/.muttrc
}

# 更新
fupdate()
{
    Operate="更新"
    [ $InstallFlag -eq 1 ] && Operate="安装"
    [ $RemoveFlag -ne 1 ] && fbackup

    cd $AppSrcBase
    test -d "$AppSrcDir" && rm -rf $AppSrcDir

    tar jxf $AppSrcFile || tar zxf $AppSrcFile
    cd $AppSrcDir

    ./configure --prefix=$AppDir && make && make install
    if [ $? -eq 0 ]; then
        echo "$AppName $Operate成功"
    else
        echo "$AppName $Operate失败"
        exit 1
    fi
}

ScriptDir=$(dirname $0)
ScriptFile=$(basename $0)
case "$1" in
    "install"   ) finstall;;
    "update"    ) fupdate;;
    "reinstall" ) fremove && finstall;;
    "remove"    ) fremove;;
    "backup"    ) fbackup;;
    "cpconf"    ) fcpconf;;
    *           )
    echo "$ScriptFile install              安装 $AppName"
    echo "$ScriptFile update               更新 $AppName"
    echo "$ScriptFile reinstall            重装 $AppName"
    echo "$ScriptFile remove               删除 $AppName"
    echo "$ScriptFile backup               备份 $AppName"
    echo "$ScriptFile cpconf               拷贝 $AppName 配置"
    ;;
esac
